package com.example.sxt_practise.thread;

import java.util.Objects;

/**
 * 多线程模拟龟兔赛跑
 * @author gaofeng
 * @date 2022年05月24日 22:18
 */
public class Race implements Runnable{

    private static String winner ;

    public static void main(String[] args) {
        new Thread(new Race(), "乌龟").start();
        new Thread(new Race(), "兔子").start();
    }

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            // 判断比赛是否结束
            if (gameOver(i)) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
        }
    }

    /**
     * 判断比赛是否结束
     * @param steps 步数
     */
    private boolean gameOver(int steps) {
        if (Objects.nonNull(winner)) {
            return true ;
        } else {
            if (steps >= 100) {
                winner = Thread.currentThread().getName() ;
                System.out.println("winner is :" + winner);
                return true ;
            }
        }
        return false ;
    }
}
